package admin.controllers;

import helpers.StringHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.Category;

import admin.models.CategoryModel;

public class CategoryArrangeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String parentId = (String) request.getParameter("parentId");
		
		CategoryModel categoryModel  = CategoryModel.getInstance();
		List<Category> categories = new ArrayList<Category>();
		if (parentId == null) {
			categories = categoryModel.listWithLevel(1);
		} else {
			categories = categoryModel.listChildren(parentId);
		}
		
		List<Category> cats =  categoryModel.getAll();
		
		request.setAttribute("categories", categories);
		request.setAttribute("cats", cats);
		request.setAttribute("parentId", parentId);
		try {
			request.getRequestDispatcher("/admin/pages/category_arrange.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		CategoryModel categoryModel  = CategoryModel.getInstance();
		
		String parentId = (String) request.getParameter("parentId");
		String strIds = (String) request.getParameter("ids");
		if (strIds != null) {
			List<String> ids = StringHelper.splitString(strIds, ",");
			categoryModel.reUpdateOrder(ids);
			request.setAttribute("success", "Update Order success.");
		}
		
		List<Category> categories = new ArrayList<Category>();
		if (parentId == null) {
			categories = categoryModel.listWithLevel(1);
		} else {
			categories = categoryModel.listChildren(parentId);
		}
		
		List<Category> cats =  categoryModel.getAll();
		
		request.setAttribute("categories", categories);
		request.setAttribute("cats", cats);
		request.setAttribute("parentId", parentId);
		try {
			request.getRequestDispatcher("/admin/pages/category_arrange.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
